package org.grill.clovercash;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.grill.clovercash.accounts.Account;
import org.grill.clovercash.storage.Reconciliation;

public class ReconcileAccountAction extends Action {
	private AccountListView view;

	public ReconcileAccountAction(AccountListView view) {
		super("Reconcile Account...");
		this.view = view;
	}
	
	@Override
	public void run() {
		IStructuredSelection sel = (IStructuredSelection) view.getViewer().getSelection();
		
		Object firstElement = sel.getFirstElement();
		if (firstElement == null) 
			return;
		
		Account a = (Account) firstElement;
		
		if (a.getReconciliation() == null) {
			ReconciliationEditDialog dlg = new ReconciliationEditDialog(view.getViewSite().getShell());
			dlg.setAccount(a);
			
			if (dlg.open() != IDialogConstants.OK_ID)
				return;
			
			Reconciliation rec = new Reconciliation(a);
			rec.setDate(dlg.getDate());
			rec.setEndAmount(dlg.getEndAmount());
			rec.setRecurse(dlg.isRecurse());
			a.setReconciliation(rec);
			if (rec.isRecurse())
				rec.addIntraAccountTransactions();
			CloverCashUIPlugin.getDefault().getRootAccount().changed(null);
		}
		
		// create new reconciliation view
		try {
			ReconcileView newView = (ReconcileView) view.getViewSite().getPage().showView(ReconcileView.ID, a.getDisplayName(), IWorkbenchPage.VIEW_ACTIVATE);
			if (!newView.isInitialized())
				newView.initialize(a.getReconciliation());
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
}	
